import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: ["*:*:*"],
      companyName: '',
      mobile: '',
      sex: 0,
    }),
    actions: {
      // 登录
      login(userInfo) {
        let data = {
          mobile: userInfo.mobile.trim(),
          type: userInfo.type,
        }
        if (userInfo.type === 1) {
          data.password = userInfo.password
        } else {
          data.yzm = userInfo.yzm
        }
        return new Promise((resolve, reject) => {
          login(data).then(res => {
            console.log('login res:', res)
            setToken(res.data.token)
            this.token = res.data.token
            this.realname = res.data.user.realname
            this.mobile = res.data.user.mobile
            this.id = res.data.user.id
            this.avatar = res.data.user.avatar
            this.sex = res.data.user.sex
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            console.log('getInfo:', res)
            const user = res.data
            if (res.data.roles && res.data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.data.roles
              this.permissions = res.data.permissions
            } else {
              this.roles = ['admin']
            }
            this.id = user.userId
            this.name = user.userName
            this.avatar = user.avatar
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          // this.token = ''
          // this.roles = []
          // this.permissions = []
          // removeToken()
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 强制退出
      forceOut() {
        return new Promise((resolve, reject) => {
          this.token = ''
          this.roles = []
          this.permissions = []
          removeToken()
          resolve()
        })
      }
    }
  })

export default useUserStore
